// com.code.exam.config.WebConfig.java

package com.code.exam.config;

import com.code.exam.interceptor.JwtTokenCommonInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Web 配置类：注册拦截器、静态资源、消息转换器等
 */
@Configuration
@Slf4j
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private JwtTokenCommonInterceptor jwtTokenCommonInterceptor;

    /**
     * 注册拦截器
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        log.info(" 开始注册 JWT 拦截器...");

        registry.addInterceptor(jwtTokenCommonInterceptor)
                .addPathPatterns("/user/**")        // 拦截所有用户接口
                .addPathPatterns("/admin/**")       // 拦截所有管理员接口
                .excludePathPatterns(
                        "/user/login",                 // 放行学生登录
                        "/admin/login",                // 放行管理员登录
                        "/doc.html",                   // 放行 Swagger
                        "/webjars/**",
                        "/swagger-resources",
                        "/v2/api-docs"
                );

        log.info("拦截器注册成功");
    }

    /**
     * 设置静态资源映射
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/doc.html")
                .addResourceLocations("classpath:/META-INF/resources/");

        registry.addResourceHandler("/webjars/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/");
    }

    /**
     * 扩展消息转换器（使用自定义 Jackson 配置）
     */
    @Override
    public void extendMessageConverters(java.util.List<org.springframework.http.converter.HttpMessageConverter<?>> converters) {
        log.info(" 扩展消息转换器...");

        // 创建自定义 JSON 转换器
        org.springframework.http.converter.json.MappingJackson2HttpMessageConverter converter =
                new org.springframework.http.converter.json.MappingJackson2HttpMessageConverter();


        converter.setObjectMapper(new com.code.exam.common.json.JacksonObjectMapper());


        converters.add(0, converter);
    }
}